<template>
  <van-button
    class="follow-btn"
    icon="success"
    round
    size="small"
    v-if="ifFollowed"
    @click="onFollow"
    :loading="isFollowLoading"
    loading-type="spinner"
    >已关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    @click="onFollow"
    :loading="isFollowLoading"
    loading-type="spinner"
    >关注</van-button
  >
</template>

<script>
export default {
  name: 'FollowUser',
  data() {
    return {
      isFollowLoading: false // 控制关注按钮加载中状态
    }
  },
  props: {
    // 是否关注
    ifFollowed: {
      type: Boolean,
      required: true
    },

    // 作者 id
    userId: {
      type: [Number, String],
      required: true
    }
  },
  model: {
    prop: 'ifFollowed',
    event: 'update-is-followed'
  },
  methods: {
    async onFollow() {
      this.isFollowLoading = true
      try {
        if (this.ifFollowed) {
          // 已关注要取消
          await this.$api.deleteFollow(this.userId)
        } else {
          // 未关注要关注
          await this.$api.addFollow(this.userId)
        }
        // 更新视图
        this.$emit('update-is-followed', !this.ifFollowed)
      } catch (err) {
        let msg = '操作失败请稍后重试'
        if (err.response && err.response.status === 400) {
          msg = '不能关注自己'
        }
        this.$toast.fail(msg)
      }
      this.isFollowLoading = false
    }
  }
}
</script>

<style></style>
